<template>
  <div class="forgot-password">
    <el-form ref="forgotForm" :model="forgotForm" :rules="forgotRules" class="forgot-form">
      <h3 class="title">找回密码</h3>
      <p class="subtitle">请输入您的用户名和企业邮箱，我们将向您的邮箱发送密码重置链接</p>

      <el-form-item prop="username">
        <el-input
          ref="usernameRef"
          v-model="forgotForm.username"
          placeholder="用户名"
          name="username"
          type="text"
          autocomplete="on">
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>

      <el-form-item prop="email">
        <el-input
          v-model="forgotForm.email"
          placeholder="企业邮箱"
          name="email"
          type="email"
          autocomplete="on">
          <svg-icon slot="prefix" icon-class="email" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>

      <el-form-item style="width: 100%">
        <el-button :loading="loading" size="medium" type="primary" style="width: 100%" @click.native.prevent="handleSubmit">
          <span v-if="!loading">发送重置链接</span>
          <span v-else>发送中...</span>
        </el-button>
      </el-form-item>

      <div class="back-link">
        <el-link type="primary" @click="goToLogin">返回登录</el-link>
      </div>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <!-- <span>Copyright © 2018-2021 django-vue-admin.com All Rights Reserved.</span> -->
    </div>
  </div>
</template>

<script>
import { sendPasswordResetEmail } from "@/api/vadmin/login";

export default {
  name: "ForgotPassword",
  data() {
    const validateEmail = (rule, value, callback) => {
      const emailRegex = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
      if (!value) {
        callback(new Error("请输入邮箱地址"));
      } else if (!emailRegex.test(value)) {
        callback(new Error("请输入有效的邮箱地址"));
      } else {
        callback();
      }
    };
    
    return {
      forgotForm: {
        username: "",
        email: ""
      },
      forgotRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入用户名" }
        ],
        email: [
          { required: true, trigger: "blur", message: "请输入企业邮箱" },
          { validator: validateEmail, trigger: "blur" }
        ]
      },
      loading: false
    };
  },
  watch: {
    // 监听邮箱变化，自动提取用户名
    'forgotForm.email': function(val) {
      if (val && !this.forgotForm.username) {
        // 如果有邮箱且用户名为空，自动提取用户名
        const emailUsername = val.split('@')[0];
        if (emailUsername) {
          this.forgotForm.username = emailUsername;
        }
      }
    }
  },
  mounted() {
    // 聚焦用户名输入框
    this.$nextTick(() => {
      this.$refs.usernameRef && this.$refs.usernameRef.focus();
    });
  },
  methods: {
    handleSubmit() {
      this.$refs.forgotForm.validate(valid => {
        if (valid) {
          this.loading = true;
          // 构造API请求参数，确保与后端API格式一致
          const data = {
            username: this.forgotForm.username,
            email: this.forgotForm.email
          };
          
          sendPasswordResetEmail(data.username, data.email)
            .then(() => {
              this.$notify({
                title: "成功",
                message: "重置链接已发送至您的邮箱，请查收并按照邮件中的指引完成密码重置",
                type: "success",
                duration: 5000
              });
              setTimeout(() => {
                this.goToLogin();
              }, 2000);
            })
            .catch(error => {
              console.error(error);
              this.$notify.error({
                title: "错误",
                message: "发送重置链接失败，请检查用户名和邮箱是否正确",
                duration: 5000
              });
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    goToLogin() {
      this.$router.push("/login");
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.forgot-password {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
}

.title {
  margin: 0px auto 20px auto;
  text-align: center;
  color: #707070;
}

.subtitle {
  font-size: 14px;
  color: #606266;
  text-align: center;
  margin-bottom: 25px;
  line-height: 1.5;
}

.forgot-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
  
  .back-link {
    text-align: center;
    margin: 15px 0;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
</style> 